package productconsume;

/**
 * @Author ufo
 * @Description TODO
 * @Date 2021/1/19 17:42
 * @Version 1.0
 */
public class PCsynchronized {
    public static void main(String[] args) {
        Tasksynchronized task = new Tasksynchronized();
        System.out.println("=====开始=======");
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    task.increase();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "a").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    task.increase();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "b").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    task.increase();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "c").start();
        new Thread(() -> {
            try {
                for (int i = 0; i < 30; i++) {
                    task.derease();

                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "d").start();

    }


}

class Tasksynchronized {
    int num = 0;

    public synchronized void increase() throws InterruptedException {
        while(num >=10) {
            this.wait();
        }
        this.num++;
        System.out.println(Thread.currentThread().getName()+":"+this.num);

        this.notifyAll();

    }

    public synchronized void derease() throws InterruptedException {
        while (num == 0) {
            this.wait();
        }
        this.num--;
        System.out.println(Thread.currentThread().getName()+":"+this.num);
        this.notifyAll();

    }
}
